package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R addAddressBook(@RequestBody AddressBook addressBook, HttpSession httpSession){
        //用户id：登陆人的用户id
        Long userId = UserHolder.getUserId();
        addressBook.setUserId(userId);
        boolean save = addressBookService.save(addressBook);
        return save?R.success("保存地址成功"):R.error("保存地址失败");
    }



    @PutMapping("/default")
    public R setDefault(@RequestBody AddressBook addressBook){
        return addressBookService.setDefault(addressBook);
    }


    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        AddressBook byId = addressBookService.getById(id);
        return R.success(byId);
    }

    @GetMapping("/list")
    public R list(){
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId,UserHolder.getUserId());
        List<AddressBook> list = addressBookService.list(qw);
        return R.success(list);
    }


    @GetMapping("/default")
    public R getDefault(){

        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId,UserHolder.getUserId());
        qw.eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookService.getOne(qw);
        return R.success(one);
    }

}
